<?php
namespace api\modules\mp\controllers;

use api\modules\mp\models\Boat;
use api\modules\mp\models\Cabin;
use api\modules\mp\models\Enroll;
use api\modules\mp\models\EnrollBatch;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use Yii;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;

class BoatController extends Controller {

    public $enableCsrfValidation = false;

    public function behaviors() {
        return array_merge(parent::behaviors(), [
            [
                'class' => 'yii\filters\auth\QueryParamAuth',
                'tokenParam' => 'session',
            ],
        ]);
    }

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    public function actionIndex() {
        $r = Boat::getList();
        return [
            'code' => 200,
            'data' => ['list' => $r]
        ];
    }

    public function actionMy() {

    }

    public function actionInfo() {
        $id = Yii::$app->request->get('id');
        $info = (Boat::build(['id' => (int)$id]))->info();
        $cabins = Cabin::getList("boat_id=$id");
        $info['cabins']=$cabins;
        return [
            'code' => 200,
            'data' => ['info' => $info]
        ];
    }

    public function actionSave() {
        $data = Yii::$app->request->post();
        $data['openid'] = Yii::$app->user->getIdentity()->openid;
        $cabinsData = ArrayHelper::remove($data, 'cabins');
        $cabins = [];
        if (!is_array($cabinsData) || count($cabinsData) < 1) return [
            'code' => 401,
            'msg' => '船舱数错误',
        ];
        foreach ($cabinsData as $cabinData) {
            $cabin = new Cabin();
            if ($id = ArrayHelper::remove($cabinData, 'id')) {
                $one = Cabin::getOne("id=$id");
                if (!$one) throw new NotFoundHttpException();
                $cabin->setAttributes($one, false);
            }
            $cabin->load($cabinData, '');
            if (!$cabin->validate()) return [
                'code' => 401,
                'msg' => current($cabin->getFirstErrors()),
                'field' => key($cabin->getFirstErrors())
            ];
            $cabins[] = $cabin;
        }
        $model = new Boat();
        if ($id = ArrayHelper::remove($data, 'id')) {
            $one = Boat::getOne("id=$id");
            if (!$one) throw new NotFoundHttpException();
            $model->setAttributes($one, false);
            if ($model->openid != $data['openid']) throw new UnauthorizedHttpException();
        }
        $model->load($data, '');
        if ($model->validate()) {
            $t = Yii::$app->db->beginTransaction();
            try {
                $model->save();
                $boatId = $model->id;
                foreach ($cabins as $cabin) {
                    if ($cabin->boatId && $cabin->boatId != $boatId) {
                        $t->rollBack();
                        return [
                            'code' => 401,
                            'msg' => '未授权'
                        ];
                    }
                    $cabin->boatId = $boatId;
                    $cabin->save();
                }
                $t->commit();
            } catch (\Exception  $e) {
                $t->rollBack();
                Yii::error($e->getMessage(), __METHOD__);
                return [
                    'code' => 500,
                    'msg' => '服务器错误'
                ];
            }
            return [
                'code' => 200,
                'data' => ['id' => $model->id]
            ];
        } else {
            return [
                'code' => 401,
                'msg' => current($model->getFirstErrors()),
                'field' => key($model->getFirstErrors())
            ];
        }
    }

    public function actionPublish() {
        $id = Yii::$app->request->post('id');
        (new Boat(['id' => $id]))->publish();
        return ['code' => 200,];
    }

    public function actionCancel() {
        $id = Yii::$app->request->post('id');
        (new Boat(['id' => $id]))->cancel();
        return ['code' => 200,];
    }

    public function actionEnroll(){
        $data=Yii::$app->request->post();
        $data['openid'] = Yii::$app->user->getIdentity()->openid;
        $clientsData = ArrayHelper::remove($data, 'clients');
        $enrolls = [];
        if (!is_array($clientsData) || count($clientsData) < 1) return [
            'code' => 401,
            'msg' => '客户数错误',
        ];
        foreach ($clientsData as $clientData) {
            $enroll = new Enroll();
            if ($id = ArrayHelper::remove($clientData, 'id')) {
                $one = Enroll::getOne("id=$id");
                if (!$one) throw new NotFoundHttpException();
                $enroll->setAttributes($one, false);
            }
            $enroll->load($clientData, '');
            if (!$enroll->validate()) return [
                'code' => 401,
                'msg' => current($enroll->getFirstErrors()),
                'field' => key($enroll->getFirstErrors())
            ];
            $enrolls[] = $enroll;
        }
        $model = new EnrollBatch();
        if ($id = ArrayHelper::remove($data, 'id')) {
            $one = EnrollBatch::getOne("id=$id");
            if (!$one) throw new NotFoundHttpException();
            $model->setAttributes($one, false);
            if ($model->openid != $data['openid']) throw new UnauthorizedHttpException();
        }
        $model->load($data, '');
        if ($model->validate()) {
            $t = Yii::$app->db->beginTransaction();
            try {
                $model->save();
                foreach ($enrolls as $enroll) {
                    $enroll->batchId = $model->id;
                    $enroll->boatId = $model->boatId;
                    $enroll->openid = $data['openid'];
                    $enroll->save();
                }
                $t->commit();
            } catch (\Exception  $e) {
                $t->rollBack();
                Yii::error($e->getMessage(), __METHOD__);
                return [
                    'code' => 500,
                    'msg' => '服务器错误'
                ];
            }
            return [
                'code' => 200,
                'data' => ['id' => $model->id]
            ];
        } else {
            return [
                'code' => 401,
                'msg' => current($model->getFirstErrors()),
                'field' => key($model->getFirstErrors())
            ];
        }
    }
    public function actionManage(){

    }
    public function actionConfirm(){

    }
    public function actionReject(){

    }
}
